package com.Policing.Receive;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Since_case.Since_case;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.Policing.Adapter.Receive_da;
import com.Policing.Shift.Allot_unit;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.CanniBalize.Shift_site;
import com.Policing.bean.Input_item;
import com.Policing.bean.Receive_add_bean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/1/3.
 */

public class Receive_add extends Activity implements OnDismissListener {
    private Button uploading;//上传
    private LinearLayout department; //领用部门
    private String department_id="";//部门id
    private LinearLayout recipient,add_place; //领用人,地点,管理人
    private TextView recipient_name;//领用名,管理人
    private String recipient_id,recipient_user,json;//领用id
    private Calendar cal;
    private Handler handler = new Handler();
    private String site_id="",JSON="";
    private List<Input_item> data = new ArrayList<>();
    //   private EditText num;//数量
    private Button scan_img;
    private TextView place;
    private EditText remark;//备注
    private String url,add_url;
    private TextView department_name;//部门名字
    private int year, month, day;
    private AlertView mAlertView;
    private ImageView fh;
    private String id;
    private ListView lv_list;
    List<Map<String, Object>> list_data = new ArrayList<Map<String, Object>>();
    private List<String> assetIds = new ArrayList<>();
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private TextView title_text;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.receive_add);
        url = "http://"+ Ip_Set.IP+"/api/receivesInspect";
        add_url = "http://"+ Ip_Set.IP+"/api/receivesAdd";
        inview();
        //获取当前日期
        getDate();

    }

    private void inview() {
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        String name = mm.getString("name","");
        id = mm.getString("id","");
        lv_list = (ListView) findViewById(R.id.fragment2_list);
        scan_img  = (Button) findViewById(R.id.scan_img);
        add_place = (LinearLayout) findViewById(R.id.add_place);
        place = (TextView) findViewById(R.id.place);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("添加领用");
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
       // num = (EditText) findViewById(R.id.receive_quantity);
        remark = (EditText) findViewById(R.id.receive_remark);
       // category_name = (TextView) findViewById(R.id.receive_category);
        recipient_name = (TextView) findViewById(R.id.receive_recipient);
        department_name = (TextView) findViewById(R.id.receive_section);
        uploading = (Button) findViewById(R.id.upload);
        department = (LinearLayout) findViewById(R.id.add_department);
        recipient = (LinearLayout) findViewById(R.id.add_recipient);
    /*    category.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Receive_add.this,add_category.class);
                startActivityForResult(intent,3);
            }
        });*/

        department.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    recipient_name.setText("");
                    recipient_id="";
                    Intent intent = new Intent(Receive_add.this, Allot_unit.class);
                    intent.putExtra("status","2");
                    startActivityForResult(intent,2);
            }
        });
        recipient.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!department_name.getText().toString().equals("")) {
                    Intent intent = new Intent(Receive_add.this, add_recipient.class);
                    intent.putExtra("department_id", department_id);
                    startActivityForResult(intent,2);
                }
            }
        });
       /* department.setOnClickListener(new View.OnClickListener() {//获取部门信息
            @Override
            public void onClick(View v) {
                    Intent dept = new Intent(Receive_add.this,add_department.class);
                    startActivityForResult(dept,2);

            }
        });*/

        uploading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // Log.i("datadata",JSON);
                if (list_data.size()>0){
                    if (!recipient_name.getText().toString().equals("")&&!site_id.equals("")&&!department_id.equals("")){
                        load();
                    }else {Toast.makeText(Receive_add.this,"请完善数据",Toast.LENGTH_SHORT).show();
                    }
                }else  Toast.makeText(Receive_add.this,"请添加需要领用的资产",Toast.LENGTH_SHORT).show();

            }
        });
        add_place.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent dept = new Intent(Receive_add.this,Shift_site.class);
                startActivityForResult(dept,3);
            }
        });
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Receive_add.this,add_category.class);
                startActivityForResult(intent,6);
            }
        });
        /*lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int i, long id) {
                    new AlertView(" 提示！", "是否删除", "取消",new String[]{"确定"}, null, Receive_add.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){

                            for (int j=0;j<lv_data.size();j++){
                                if (lv_data.get(j).equals(data.get(i).getCode_number())){
                                    lv_data.remove(j);
                                }
                            }
                            data.remove(i);
                            Input_Adapter_item adapter_item = new Input_Adapter_item(Receive_add.this,R.layout.input_adapter_item,data);
                            lv_list.setAdapter(adapter_item);
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(Receive_add.this).show();
            }
        });*/
    }

    private void load( ) {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("source", Since_case.set().getSource())
                            .add("receivesDept",department_id)
                            .add("place", site_id)
                            .add("json",JSON)
                            .add("company","")
                            //.add("receivesUser",recipient_user)
                            .add("receivesUser",recipient_id)
                            .add("id",id)
                            .add("receivesRemark", remark.getText().toString())
                            .build();
                    Request request = new Request.Builder()
                            .url(add_url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("222",responseData);
                    showResponse_load(responseData);//解析

                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }.start();
    }
    private void showResponse_load(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                JSONObject js = null;
                try {
                    js = new JSONObject(responseData);
                    if (js.getString("state").equals("0")){
                        Toast.makeText(Receive_add.this,"提交失败",Toast.LENGTH_SHORT).show();
                    }
                    if (js.getString("state").equals("1")){

                        Toast.makeText(Receive_add.this,"申请成功",Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    if (js.getString("state").equals("2")){
                        new AlertView("申请添加成功", "是否继续添加", "取消",new String[]{"确定"}, null, Receive_add.this, AlertView.Style.Alert, new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {
                                //取消：position=-1,确定 position=0
                                if (position==0){
                                    //Toast.makeText(Receive_add.this,"申请添加成功",Toast.LENGTH_SHORT).show();
                                  /*  category_name.setText("");
                                    num.setText("");*/
                                }

                            }
                        }).setCancelable(true).setOnDismissListener(Receive_add.this).show();


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }


    //获取当前日期
    private void getDate() {
        cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);       //获取年月日时分秒
        month = cal.get(Calendar.MONTH);   //获取到的月份是从0开始计数
        day = cal.get(Calendar.DAY_OF_MONTH);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==2&&resultCode==1){
            department_id = data.getExtras().getString("dept_id");
            String name = data.getExtras().getString("dept_name");
            department_name.setText(name);
        }
        if (requestCode==2&&resultCode==3){
            recipient_name.setText(data.getExtras().getString("recipient_name"));
            recipient_id = data.getExtras().getString("recipient_id");
            recipient_user=data.getExtras().getString("recipient_name");
        }
      /*  if (requestCode==3&&resultCode==3){
            category_name.setText(data.getExtras().getString("category_name"));
            category_id = data.getExtras().getString("category_id");
        }*/
        if (requestCode==3&&resultCode==3){
            place.setText(data.getExtras().getString("site_name"));
            site_id = data.getExtras().getString("site_id");

        }
        if (requestCode==6&&resultCode==6){
           JSON =  data.getExtras().getString("data");
            Gson gson = new Gson();
            List<Receive_add_bean> userList = gson.fromJson(data.getExtras().getString("list"), new TypeToken<List<Receive_add_bean>>(){}.getType());
            for(int i = 0;i < userList.size();i++){
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("coding_name",userList.get(i).getName());
                map.put("receivesDept_name",userList.get(i).getNum());
                map.put("receivesUser_name",userList.get(i).getUser());
                map.put("reapplyDate_name",userList.get(i).getPlace());
                list_data.add(map);
            }
            Receive_da receive_da = new Receive_da(Receive_add.this,list_data);
            lv_list.setAdapter(receive_da);

        }
    }

    @Override
    public void onDismiss(Object o) {

    }
}
